package com.zhoug.bluetooth;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;


import com.zhoug.logging.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 蓝牙连接管理
 *
 * @Author: zhoug
 * @Date: 2024-06-25
 * @Description:
 */
@SuppressLint("MissingPermission")
public class ZBluetoothManager {
    private static final String TAG = ">>>zbluetooth";
    private final BluetoothAdapter mBluetoothAdapter;
    private OnBluetoothListener mOnBluetoothListener;
    private final Object mTarget;
    private ActivityResultLauncher<Intent> mScreenCaptureLauncher;
    private List<BluetoothDevice> mDevices = new ArrayList<>();
    private int mDeviceType = 0;

    public ZBluetoothManager(@NonNull FragmentActivity target) {
        mTarget = target;
        addObserver(target.getLifecycle());
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    private void addObserver(Lifecycle lifecycle) {
        lifecycle.addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                registerBroadcastReceiver();
                if (mTarget instanceof FragmentActivity) {
                    Logger.d(TAG, "注册蓝牙开启回调");
                    mScreenCaptureLauncher = ((FragmentActivity) mTarget).registerForActivityResult(
                            new ActivityResultContracts.StartActivityForResult(),
                            result -> {
                                if (result != null) {
                                    if (mOnBluetoothListener != null) {
                                        mOnBluetoothListener.onBluetoothEnable(result.getResultCode() == Activity.RESULT_OK);
                                    }
                                }
                            }
                    );
                }
            }

            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                if (mScreenCaptureLauncher != null) {
                    mScreenCaptureLauncher.unregister();
                }
                unregisterBroadcastReceiver();
            }
        });
    }

    /**
     * 指定设备类型
     *
     * @param deviceType 如打印机 {@link android.bluetooth.BluetoothClass.Device#AUDIO_VIDEO_PORTABLE_AUDIO}
     */
    public void setDeviceType(int deviceType) {
        this.mDeviceType = deviceType;
    }

    /**
     * 当前设备是否支持蓝牙
     *
     * @return
     */
    public boolean isSupportBluetooth() {
        return null != mBluetoothAdapter;
    }

    /**
     * 蓝牙是否打开
     *
     * @return
     */
    public boolean isOpenBluetooth() {
        return isSupportBluetooth() && mBluetoothAdapter.isEnabled();
    }

    /**
     * 打开蓝牙
     */
    public void openBluetooth() {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        mScreenCaptureLauncher.launch(enableIntent);
        Logger.d(TAG, "打开蓝牙");
    }


    /**
     * 获取绑定
     *
     * @param scan true:开启扫描,false:不开启扫描只获取已经配对成功的设备
     */
    public void findDevices(boolean scan) {
        if (isSupportBluetooth()) {
            Logger.d(TAG, "获取已经配对的设备");
            Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
            mDevices.clear();
            if (bondedDevices != null && !bondedDevices.isEmpty()) {
                if (mDeviceType == 0) {
                    mDevices.addAll(bondedDevices);
                } else {
                    for (BluetoothDevice item : bondedDevices) {
                        if (isMatchDeviceType(item)) {
                            mDevices.add(item);
                        }
                    }
                }
            }
            mOnBluetoothListener.onBluetoothDeviceChange(mDevices);
            if (scan) {
                startScanning();
            }
        }
    }

    /**
     * 是否是给定的设备类型
     *
     * @param device
     * @return
     */
    private boolean isMatchDeviceType(BluetoothDevice device) {
        return mDeviceType == 0 || ((BluetoothUtil.getDeviceType(device) & mDeviceType) == mDeviceType);
    }


    /**
     * 开启扫描蓝牙设备
     */
    public boolean startScanning() {
        boolean s = false;
        if (isSupportBluetooth() && !mBluetoothAdapter.isDiscovering()) {
            s = mBluetoothAdapter.startDiscovery();
        }
        Logger.d(TAG, "开启扫描蓝牙设备:" + s);
        return s;
    }

    /**
     * 取消扫描蓝牙设备
     */
    public boolean cancelScanning() {
        boolean s = false;
        if (isSupportBluetooth() && mBluetoothAdapter.isDiscovering()) {
            s = mBluetoothAdapter.cancelDiscovery();
        }
        Logger.d(TAG, "取消扫描蓝牙设备:" + s);
        return s;
    }

    public void setOnBluetoothListener(OnBluetoothListener onBluetoothListener) {
        this.mOnBluetoothListener = onBluetoothListener;
    }


    private void registerBroadcastReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
        if (mTarget instanceof Activity) {
            Logger.d(TAG, "注册广播");
            ((Activity) mTarget).registerReceiver(mBluetoothDeviceReceiver, filter);
        }
    }

    private void unregisterBroadcastReceiver() {
        if (mTarget instanceof Activity) {
            Logger.d(TAG, "取消注册广播");
            ((Activity) mTarget).unregisterReceiver(mBluetoothDeviceReceiver);
        }
    }


    private final BroadcastReceiver mBluetoothDeviceReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
//            Logger.d(TAG, "蓝牙广播 onReceive:"+action);
            if (LocationManager.PROVIDERS_CHANGED_ACTION.equals(action)) {
                //监听GPS服务状态
                if(mOnBluetoothListener!=null){
                    mOnBluetoothListener.onGPSEnable(BluetoothUtil.isGpsOpened(context));
                }
            } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //发现设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (mOnBluetoothListener != null && isMatchDeviceType(device) && BluetoothUtil.isEffectiveDevice(device)) {
                    Logger.d(TAG, String.format("发现设备:%s:%s", device.getName(), device.getAddress()));
//                    BluetoothUtil.printUUID(device);
                    if (!mDevices.contains(device)) {
                        mDevices.add(device);
                        if (mOnBluetoothListener != null) {
                            mOnBluetoothListener.onBluetoothDeviceChange(mDevices);
                        }
                    }
                }
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                //配对状态改变
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (isMatchDeviceType(device) && BluetoothUtil.isEffectiveDevice(device) && mOnBluetoothListener != null) {
                    Logger.d(TAG, String.format("配对状态改变:%s:%s", device.getName(), BluetoothUtil.getBondStateName(device.getBondState())));
                    mOnBluetoothListener.onDeviceBondStateChange(device);
                }
            } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (isMatchDeviceType(device) && BluetoothUtil.isEffectiveDevice(device) && mOnBluetoothListener != null) {
                    Logger.d(TAG, String.format("设备已连接:%s:%s", device.getName(), device.getAddress()));
                    mOnBluetoothListener.onDeviceConnectStateChange(device, true);
                }
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (isMatchDeviceType(device) && BluetoothUtil.isEffectiveDevice(device) && mOnBluetoothListener != null) {
                    Logger.d(TAG, String.format("设备已断开:%s:%s", device.getName(), device.getAddress()));
                    mOnBluetoothListener.onDeviceConnectStateChange(device, false);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
                Logger.d(TAG, "开始扫描蓝牙设备");
                if (mOnBluetoothListener != null) {
                    mOnBluetoothListener.onScanning(true);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                Logger.d(TAG, "结束扫描蓝牙设备");
                if (mOnBluetoothListener != null) {
                    mOnBluetoothListener.onScanning(false);
                }
            }
        }
    };


}
